package cn.storm.codehelper.util

import cn.storm.codehelper.model.MethodType
import com.intellij.psi.PsiClass

/**
 * 获取当前类和父类
 */
fun getClassLinkList(psiClass: PsiClass): List<PsiClass> {
    val psiClasss = mutableListOf<PsiClass>()
    var currentPsiClass: PsiClass? = psiClass
    while (currentPsiClass.isNotNull() && "Object" != currentPsiClass!!.name) {
        psiClasss.add(currentPsiClass)
        currentPsiClass = currentPsiClass.superClass
    }
    return psiClasss.reversed()

}

/**
 * 获取所有方法
 */
fun getMethods(psiClass: PsiClass, type: String): List<String> {
    val staticFinalReg = Regex("static.*?final|final.*?static")
    val methodType = MethodType.valueOf(type.uppercase())
    val reMethods = mutableListOf<String>()
    if (isUseLombok(psiClass, methodType)) {
        psiClass.fields.forEach loop@{
            val fieldVal = it.nameIdentifier.context?.text ?: ""
            if (fieldVal.contains("serialVersionUID")) {
                return@loop
            }
            val find = staticFinalReg.find(fieldVal)
            if (find.isNotNull()) {
                return@loop
            }
            val name = it.nameIdentifier.text
            reMethods.add("$type${name.replaceFirstChar { f -> f.uppercase() }}")
        }
    }
    //获取方法
    psiClass.methods.forEach {
        val methodName = it.name
        if (methodType.regex.find(methodName).isNotNull()
            && !reMethods.contains(methodName)) {
            reMethods.add(methodName)
        }
    }
    return reMethods

}

/**
 * 是否使用了lombok
 */
fun isUseLombok(psiClass: PsiClass, methodType: MethodType): Boolean {
    return psiClass.getAnnotation("lombok.Data") != null
            || psiClass.getAnnotation(methodType.lombokStr) != null
}
